package web

import (
	"encoding/json"
	"go-quick/interface/ilogger"
	"io"
	"net/http"
)

type HttpResponse struct {
	log      ilogger.ILogger
	response http.ResponseWriter
}

func NewHttpResponse(logger ilogger.ILogger, response http.ResponseWriter) *HttpResponse {
	return &HttpResponse{
		log:      logger,
		response: response,
	}
}

func (h *HttpResponse) Response() http.ResponseWriter {
	return h.response
}

func (h *HttpResponse) Header(key string, value string) {
	h.response.Header().Set(key, value)
}

func (h *HttpResponse) Headers(headerMap map[string]string) {
	if headerMap != nil && len(headerMap) > 0 {
		for k, v := range headerMap {
			h.response.Header().Set(k, v)
		}
	}
}

func (h *HttpResponse) Json(code int, data any) {
	h.response.Header().Set("Content-Type", "application/json")
	h.response.WriteHeader(code)
	encoder := json.NewEncoder(h.response)
	if err := encoder.Encode(data); err != nil {
		http.Error(h.response, err.Error(), 500)
	}
}

func (h *HttpResponse) File(header map[string]string, source io.Reader) {
	h.Headers(header)
	if _, err := io.Copy(h.response, source); err != nil {
		http.Error(h.response, err.Error(), 500)
	}
}

func (h *HttpResponse) Status(code int) {
	h.response.WriteHeader(code)
}
